const express = require('express')
const router = express.Router()
const SubCategory = require('../models/SubCategory')
const Feed = require('../models/Feed')
const Banner = require('../models/Banner')
const { baseURL } = require('../config')

/**
 * 查询所有分类
 */
router.get('/:id', async(req, res, next) => {
  const {id} = req.params
  if (id === '1') {
    let [banners, total] = await Promise.allSettled([
      Banner.find({}, {_id: false, __v: false}).limit(6),
      Feed.count({tabId: id}),
    ])
    const feeds = await Feed.find({tabId: id}, {_id: false, __v: false}).limit(20)
    const result = {banners: [], items: {}}
    if (banners.status === 'fulfilled') {
      result.banners = banners.value.map(item => {
        item.image = baseURL + item.image
        return item
      })
    }
    if (total.status === 'fulfilled') {
      total = total.value
    }
    result.items = {
      list: feeds,
      total,
      startIndex: 0,
      nextIndex: 20,
      perpage: 20,
      isEnd: total <= 20
    }
    res.json({
      code: 200,
      data: {
        ...result
      }
    })
  } else {
    let [categories, total] = await Promise.allSettled([
      SubCategory.find({parentCategoryId: id}, {_id: false, __v: false}),
      Feed.count({tabId: id}),
    ])
    const result = {categories: [], items: {}}
    if (categories.status === 'fulfilled') {
      result.categories = categories.value
    }
    if (total.status === 'fulfilled') {
      total = total.value
    }
    const feeds = await Feed.find({tabId: id}, {_id: false, __v: false}).limit(20)

    result.items = {
      list: feeds,
      total,
      startIndex: 0,
      nextIndex: 20,
      perpage: 20,
      isEnd: total <= 20
    }
    res.json({
      code: 200,
      data: {
        ...result
      }
    })
  }
})

/**
 * 查询分类下的推荐商品数据
 */
router.get('/:id/feeds', (req, res) => {
  const { id } = req.params
  const start = Number(req?.query?.start ?? 0) ?? 0
  const perpage = Number(req?.query?.perpage ?? 20)

  Feed
    .count({tabId: id})
    .then(total => {
      Feed
        .find({tabId: id}, {_id: false, __v: false})
        .limit(perpage)
        .skip(start)
        .then(data => {
          res.json({
            code: 200,
            data: {
              isEnd: start + perpage >= total,
              list: data,
              perpage,
              start,
              nextIndex: start + perpage,
              total
            }
          })
        })
        .catch(err => {})
    })
})

module.exports = router
